package com.hk.commons.query;

import com.hk.commons.util.CollectionUtils;
import com.hk.commons.util.StringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Kevin
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class OrderUtils {

    /**
     * 注意：每个关键字，可以加个空格，因为对于排序，如果使用的是 create_time 字段，不应该被过滤
     */
    private static final String REGEX = "'|%|;|--|and |or |not |use |insert |delete |update |select |count |group |union " +
            "|create |drop |truncate |alter |show |grant |execute |exec |xp_cmdshell |call |declare |source |sql ";

    public static String escape(String args) {
        return StringUtils.isEmpty(args) ? null : args.replaceAll(STR."(?i)\{REGEX}", "");
    }

    public static List<Order> escapeFilter(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders)) {
            return orders;
        }
        return orders.stream().filter(item -> {
            String escape = escape(item.getField());
            return StringUtils.equals(escape, item.getField());
        }).collect(Collectors.toList());
    }

    public static String toOrderSql(Collection<Order> orders) {
        if (CollectionUtils.isNotEmpty(orders)) {
            var orderSql = new StringBuilder();
            var index = 0;
            for (var order : orders) {
                String escape = escape(order.getField());
                if (StringUtils.equals(escape, order.getField())) {
                    if (index++ > 0) {
                        orderSql.append(StringUtils.COMMA_SEPARATE);
                    }
                    orderSql.append(order);
                }
            }
            return orderSql.isEmpty() ? StringUtils.EMPTY : orderSql.insert(0, " ORDER BY ").toString();
        }
        return StringUtils.EMPTY;
    }
}
